package updown.util;


import com.github.pagehelper.util.StringUtil;
import lombok.extern.slf4j.Slf4j;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * <p>Title: ww.kaixin.downupservice.util </p>
 * <p>Description:updown: -  </p>
 *
 * @Author:jiangkaixin
 * @Date:2021/11/3
 * @Version: 1.0
 */
@Slf4j
public class DateUtils {
    // SimpleDateFormat 在操作format 方法 和  parse 方式的时候，是线程不安全的，因为他们共享 Calander对象
    private static ThreadLocal<SimpleDateFormat> threadLocal = ThreadLocal.withInitial(SimpleDateFormat::new);

    /**
     * 日期格式(yyyy-MM-dd HH:mm:ss)
     */
    public static final String YYYY_MM_DD_HH_MM_SS_EN = "yyyy-MM-dd HH:mm:ss";

    public static String getCurDateTime() {
        return dateToDateString(new Date(), YYYY_MM_DD_HH_MM_SS_EN);
    }

    public static String dateToDateString(Date date, String formatStr) {
        DateFormat df = getDateFormat(formatStr);
        return df.format(date);
    }


    private static DateFormat getDateFormat(String formatStr) {
        DateFormat df = threadLocal.get();
        ((SimpleDateFormat) df).applyPattern(formatStr);
        return df;
    }

    /**
     * 获得两个日期相差多少分钟
     */
    public static long getSecondsBetweenNoError(String start, String end) {
        if (StringUtil.isEmpty(start) || StringUtil.isEmpty(end)) {
            return 0l;
        }
        DateFormat df = getDateFormat(YYYY_MM_DD_HH_MM_SS_EN);

        try {
            Date d1 = df.parse(start);
            Date d2 = df.parse(end);
            long minites = (d2.getTime() - d1.getTime()) / 1000;
            return minites;
        } catch (Exception e) {
            log.error("{}",e);
        }
        return 0L;
    }

    /**
     * 获得两个日期相差多少分钟
     */
    public static int getMinutesBetweenNoError(String start, String end) {
        long secondsBetweenNoError = getSecondsBetweenNoError(start, end);
        return (int) secondsBetweenNoError/60;
    }
}
